package com.geccocrawler.socks5.auth;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PropertiesPasswordAuth implements PasswordAuth {

    private static Map<String, String> users;

    static {
        users = new ConcurrentHashMap();
        try {
            // 每30秒重新读取一次password.properties
            ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
            executor.scheduleAtFixedRate(() -> {
                try {
                    Properties properties = new Properties();
                    properties.load(PropertiesPasswordAuth.class.getResourceAsStream("/password.properties"));
                    Set<String> propertyNames = properties.stringPropertyNames();
                    synchronized (users) {
                        // 刷新用户列表
                        users.clear();
                        for (String name : propertyNames) {
                            String value = properties.getProperty(name);
                            users.put(name, value);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }, 0, 30, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean auth(String user, String password) {
        String configPasword;
        synchronized (user) {
            configPasword = users.get(user);
        }
        if (configPasword != null && password.equals(configPasword)) {
            return true;
        }
        return false;
    }

}
